# -*- coding:utf-8 -*-
'''
test.py
'''
import time

import cv2

clicked = False
g_rectangle = [0, 0, 0, 0]
g_startPoint = [0, 0]
is_over = False

def onMouse(event, x, y, flags, param):
    global clicked
    global g_rectangle
    global g_startPoint
    global is_over

    if event == cv2.EVENT_MOUSEMOVE:
        if clicked == True:
            g_rectangle[0] = min(g_startPoint[0], x)
            g_rectangle[1] = min(g_startPoint[1], y)
            g_rectangle[2] = max(g_startPoint[0], x)
            g_rectangle[3] = max(g_startPoint[1], y)

    # 左键按下事件
    if event == cv2.EVENT_LBUTTONDOWN:

        g_startPoint[0] = x
        g_startPoint[1] = y
        clicked = True
    # 左键弹起事件
    if event == cv2.EVENT_LBUTTONUP:
        print("====================选中框的坐标：===========================")
        print("矩形框左上角坐标：")
        print(g_rectangle[0], g_rectangle[1])
        print("矩形框右下角坐标：")
        print(g_rectangle[2], g_rectangle[3])
        clicked = False
        is_over = True


def startRoi(img):
    global is_over
    if is_over is True:
        return False
    title_ = "ESC_EXIT".encode("gbk").decode('UTF-8', errors='ignore')
    title_ = "{}_{}".format(title_, time.time())
    cv2.namedWindow(winname=title_)
    cv2.resizeWindow(title_, 1920, 1080)  # 设置长和宽
    cv2.setMouseCallback(title_, onMouse)

    # 按"Esc"退出
    print("Press Esc if you want to exit ...")
    while cv2.waitKey(30) != 27 and is_over is False:
        global frame
        # 画矩形
        cv2.rectangle(img, (g_rectangle[0], g_rectangle[1]), (g_rectangle[2], g_rectangle[3]), (0, 255, 0), 2)
        cv2.imshow(title_, img)

    is_over = False
    cv2.destroyWindow(title_)


if __name__ == '__main__':
    path = r"F:\workspace\008581.jpg"
    startRoi(path)
